package com.erp.util;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;

import java.io.UnsupportedEncodingException;

public class SM3Util {

    /**
     * SM3 哈希计算（返回十六进制字符串）
     * @param data 原始数据
     * @return 哈希结果（64位十六进制字符串）
     */
    public static String hash(String data) {
        try {
            byte[] bytes = data.getBytes("UTF-8");
            SM3Digest digest = new SM3Digest();
            digest.update(bytes, 0, bytes.length);
            byte[] result = new byte[digest.getDigestSize()];
            digest.doFinal(result, 0);
            return Hex.toHexString(result);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 encoding not supported", e);
        }
    }

    /**
     * SM3 哈希计算（返回字节数组）
     * @param data 原始数据
     * @return 哈希结果字节数组
     */
    public static byte[] hashToBytes(String data) {
        try {
            byte[] bytes = data.getBytes("UTF-8");
            SM3Digest digest = new SM3Digest();
            digest.update(bytes, 0, bytes.length);
            byte[] result = new byte[digest.getDigestSize()];
            digest.doFinal(result, 0);
            return result;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 encoding not supported", e);
        }
    }

    // 示例用法
    public static void main(String[] args) {
        String data = "123123";
        String hash = hash(data);
        System.out.println("SM3 Hash: " + hash);
        // 输出: e6f8d9e8e9f8e8e9f8e8e9f8e8e9f8e8e9f8e8e9f8e8e9f8e8e9
    }
}
